package com.kr.aia.powerrp.common;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.kr.aia.powerrp.R;

import android.content.Context;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Environment;
import android.util.Log;
import android.util.Pair;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;

public class RecController extends SurfaceView implements SurfaceHolder.Callback {

	private Camera mCamera = null;
	private MediaRecorder mrec;
	private SurfaceHolder surfaceHolder;
	private String dataPath;
	private String dirName;
	private int camID = 0;

	public RecController(Context context, String dirname) {
		super(context);
		
		this.dirName = dirname;
		this.dataPath = Environment.getExternalStorageDirectory().getPath() + "/powerRP/" + dirName;
		initDirectories();

		surfaceHolder = this.getHolder();
		surfaceHolder.addCallback(this);
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}
	
    private void startCamera(SurfaceHolder sh, int width, int height) {
        Camera.Parameters p = mCamera.getParameters();
        
        int maxPS = p.getSupportedPreviewSizes().size()-1;
        
        /*for(int i = 0 ; i < p.getSupportedPreviewSizes().size(); i++){
        	Log.e("PRP", " =------ " +p.getSupportedPreviewSizes().get(i).width  + " -- "  + p.getSupportedPreviewSizes().get(i).height);
        }*/
        
        
        
        // Camera.Size s = p.getSupportedPreviewSizes().get(0);
        //p.setPreviewSize(1280, 720);
        p.setPictureSize(p.getSupportedPreviewSizes().get(maxPS).width, p.getSupportedPreviewSizes().get(maxPS).height);

        mCamera.setParameters(p);
        
        

        try {
        	mCamera.setPreviewDisplay(sh);
        	mCamera.startPreview();
        } catch (Exception e) {
        }
        
    }
    
    public void startRecording() throws IOException 
    {
    	if(checkSDMount()){
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
            String currentDate = sdf.format(new Date());
    		
            String fileName = currentDate+".mp4";
            
            
	    	mCamera.unlock();
	    	
	    	mrec = new MediaRecorder();  // Works well
	        mrec.setCamera(mCamera);
	        
	        /*
	        mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
	        mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
	        
	        
	        mrec.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
	        
	        mrec.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
	        mrec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
	        
	        CamcorderProfile profile = CamcorderProfile.get(CamcorderProfile.QUALITY_LOW);
	        profile.videoFrameWidth = 640;
	        //profile.videoFrameHeight = 480;
	        //zmrec.setProfile(profile);
	        //mrec.setVideoSize(1280, 800);
	        
	        mrec.setOutputFile(this.dataPath + "/" + fileName);
	        mrec.setPreviewDisplay(surfaceHolder.getSurface());
	        */
	        
	        mrec.setCamera(mCamera);

	        mrec.setPreviewDisplay(surfaceHolder.getSurface());
	        mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
	        mrec.setAudioSource(MediaRecorder.AudioSource.MIC); 
	        
	        CamcorderProfile profile = CamcorderProfile.get(camID, CamcorderProfile.QUALITY_HIGH);

	        mrec.setProfile(profile);
	        mrec.setPreviewDisplay(surfaceHolder.getSurface());
	        mrec.setOutputFile(this.dataPath + "/" + fileName);
	        
	    	mrec.prepare();
	        mrec.start();
    	}
    }

    public void stopRecording() {
        mrec.stop();
        mrec.reset();
        mrec.release();
        mrec = null;
    }
    
    public void releaseMediaRecorder(){
        if (mrec != null) {
            mrec.reset();   // clear recorder configuration
            mrec.release(); // release the recorder object
            mrec = null;
            mCamera.lock();           // lock camera for later use
        }
    }

    public void releaseCamera(){
        if (mCamera != null){
            mCamera.release();        // release the camera for other applications
            mCamera = null;
        }
    }
	
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,int height) {
		//startCamera(holder, width, height);
	}
	
	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		Camera.CameraInfo camInfo = new Camera.CameraInfo();
		int camCount = 0;
		camCount = Camera.getNumberOfCameras();
		for(int camIdx = 0 ; camIdx < camCount; camIdx++){
			Camera.getCameraInfo(camIdx, camInfo);
			if( camInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT){
				try{
					mCamera = Camera.open(camIdx);
					camID = camIdx;
				}catch(RuntimeException e){
					e.printStackTrace();
				}
			}
		}
    	
        //mCamera.setPreviewDisplay(holder);
		startCamera(holder, 1280, 800);
	}
	
	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		mCamera.stopPreview();
        mCamera.release();
	}
	
	public void initDirectories(){
		
		if(checkSDMount()){
			File dir = new File(dataPath);
			if(!dir.exists()) {
				dir.mkdirs();
			}
		}
		//Log.i("PRP", path);
	}
	
	public boolean checkSDMount(){
		Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);

		if(isSDPresent){
			//Toast toast = Toast.makeText(getContext(), "SD카드가 삽입 되었습니다.", Toast.LENGTH_SHORT); 
			//toast.show();
			return true;
		}else{
			Toast.makeText(getContext(), "SD카드가 삽입되지 않았습니다.", Toast.LENGTH_SHORT).show();
			return false;
		}
	}
}
